﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- 常用搜索条件 -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="Name_FormItem" prop="Name">
							<template #label>
								<WtmLabelTooltip label="姓名" tooltip="候选人姓名" />
							</template>
							<el-input v-model="searchData.Name" placeholder="请输入姓名" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="HrStatus_FormItem" prop="HrStatus">
							<template #label>
								<WtmLabelTooltip label="状态" tooltip="单据状态" />
							</template>
							<el-select v-model="searchData.HrStatus" clearable>
								<el-option v-for="option in HR_STATUS_OPTIONS" :key="option.value" :value="option.value" :label="option.label"></el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<!-- 可展开的详细搜索条件 -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="InterviewRequestBillId_FormItem" prop="InterviewRequestBillId">
								<template #label>
									<WtmLabelTooltip label="面试表编号" tooltip="面试表编号" />
								</template>
								<el-select v-model="searchData.InterviewRequestBillId" :data="stateData.AllSysHrInterviewRequestBills" clearable>
									<el-option
										v-for="item in stateData.AllSysHrInterviewRequestBills"
										:key="item.Value"
										:value="item.Value"
										:label="item.Text"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysHrInterviewPool/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrInterviewPool/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/syshrinterviewpool/genonboardingbyids'"
				icon="fa fa-user-plus"
				type="success"
				button-text="批量录用"
				:disabled="!hasSelectedRows"
				confirm="确定要批量录用选中的候选人吗？"
				@click="onBatchOnboarding()"
			/>
			<WtmButton
				v-auth="'/api/SysHrInterviewPool/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrInterviewPool/SysHrInterviewPoolExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable
			ref="tableRef"
			v-bind="safeTableData"
			class="table-operation-area"
			@row-edit="onRowEdit"
			@row-save="onRowSave"
			@row-cancel="onRowCancel"
			@batch-save="onBatchSave"
		>
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysHrInterviewPool/Edit'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysHrInterviewPool/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysHrInterviewPool/BatchDelete'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="录用候选池;true;HengTong.Areas.Hr.Controllers;SysHrInterviewPool">
import { ElMessage } from 'element-plus';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed, type ComponentInternalInstance } from 'vue';
import { SysHrInterviewPoolApi as api } from '/@/views/hr/syshrinterviewpool/api';
import { ISysHrInterviewPoolView, ISysHrInterviewPoolQuery } from '/@/views/hr/syshrinterviewpool/api/interface';
import other from '/@/utils/other';

// 懒加载子组件
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

// 常量定义
const HR_STATUS_OPTIONS = [
	{ value: '申请中', label: '申请中' },
	{ value: '已审核', label: '已审核' },
	{ value: '已拒绝', label: '已拒绝' },
	{ value: '已面试', label: '已面试' },
	{ value: '面试通过', label: '面试通过' },
	{ value: '面试未通过', label: '面试未通过' },
	{ value: '体检中', label: '体检中' },
	{ value: '体检通过', label: '体检通过' },
	{ value: '体检未通过', label: '体检未通过' },
	{ value: '背调中', label: '背调中' },
	{ value: '背调通过', label: '背调通过' },
	{ value: '背调未通过', label: '背调未通过' },
	{ value: 'Offer已发', label: 'Offer已发' },
	{ value: 'Offer已接受', label: 'Offer已接受' },
	{ value: 'Offer已拒绝', label: 'Offer已拒绝' },
	{ value: '已录用', label: '已录用' },
	{ value: '已入职', label: '已入职' },
	{ value: '已报到', label: '已报到' },
	{ value: '入职资料待完善', label: '入职资料待完善' },
	{ value: '试用中', label: '试用中' },
	{ value: '已转正', label: '已转正' },
	{ value: '已放弃', label: '已放弃' },
	{ value: '已淘汰', label: '已淘汰' },
	{ value: '离职办理中', label: '离职办理中' },
	{ value: '已离职', label: '已离职' },
] as const;

const API_ENDPOINTS = {
	BILLS: '/api/SysHrInterviewPool/GetSysHrInterviewRequestBills',
} as const;

const TABLE_HEADERS = [
	{ title: '面试表编号', key: 'InterviewRequestBillName', type: 'text', isCheck: true },
	{ title: '姓名', key: 'Name', type: 'text', isCheck: true },
	{ title: '工号', key: 'HiredStaffNo', type: 'text', isCheck: true, editable: true, editType: 'textbox' },
	{ title: '年龄', key: 'Age', type: 'number', isCheck: true },
	{ title: '性别', key: 'Gender', type: 'text', isCheck: true },
	{ title: '手机号', key: 'Phone', type: 'text', isCheck: true },
	{ title: '身份证号', key: 'IdCardNo', type: 'text', isCheck: true },
	{ title: '民族', key: 'Ethnicity', type: 'text', isCheck: true },
	{ title: '婚姻状况', key: 'MaritalStatus', type: 'text', isCheck: true },
	{ title: '状态', key: 'HrStatus', type: 'text', isCheck: true },
] as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysHrInterviewPoolQuery;
		/** 主表ID */
		entityId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
	}
);

const stateData = reactive({
	AllSysHrInterviewRequestBills: [] as any[],
	GenderOptions: [
		{ value: '男', label: '男' },
		{ value: '女', label: '女' },
	],
	MaritalStatusOptions: [
		{ value: '未婚', label: '未婚' },
		{ value: '已婚', label: '已婚' },
		{ value: '离异', label: '离异' },
		{ value: '丧偶', label: '丧偶' },
	],
	HrStatusOptions: HR_STATUS_OPTIONS,
});

const searchData = ref<ISysHrInterviewPoolQuery>({});
const tableRef = ref();

// 初始化表格数据
const tableData = ref({
	data: [],
	header: TABLE_HEADERS,
	config: {
		total: 0,
		loading: true,
		isSerialNo: true,
		isSelection: true,
		isOperate: !props.isDisabled,
	},
});

// 确保表格数据安全
const safeTableData = computed(() => {
	// 构建下拉框数据映射
	const comboData = {
		Gender: Object.fromEntries(stateData.GenderOptions.map((opt) => [opt.value, opt.label])),
		MaritalStatus: Object.fromEntries(stateData.MaritalStatusOptions.map((opt) => [opt.value, opt.label])),
		HrStatus: Object.fromEntries(stateData.HrStatusOptions.map((opt) => [opt.value, opt.label])),
	};

	return {
		...tableData.value,
		data: Array.isArray(tableData.value.data) ? tableData.value.data : [],
		header: Array.isArray(tableData.value.header) ? tableData.value.header : [],
		config: {
			...tableData.value.config,
			comboData, // 传递下拉框数据
		},
	};
});

// 计算属性 - 判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 初始化表格数据
const getTableData = async () => {
	try {
		if (tableRef.value) {
			await tableRef.value.doSearch(api().search, searchData.value);
		}
	} catch (error) {
		handleError(error);
	}
};

// 对话框操作
const OnCreateClick = () => {
	const data = props.entityId ? { entityId: props.entityId } : null;
	other.openDialog(ci.proxy?.$t('message._system.common.vm.add') || '新增', CreateDialog, data, getTableData, '50%');
};

const OnEditRowClick = (row: ISysHrInterviewPoolView) => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.edit') || '编辑', EditDialog, row, getTableData, '50%');
};

const OnDetailsRowClick = (row: ISysHrInterviewPoolView) => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.detail') || '详情', DetailsDialog, row, getTableData, '50%');
};

const OnImportClick = () => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.import') || '导入', ImportDialog, null, getTableData);
};

// 删除操作
const onDelete = async (row: ISysHrInterviewPoolView) => {
	try {
		const ids = [row.ID] as (string | number)[];
		await api().delete(ids);
		getTableData();
	} catch (error) {
		handleError(error);
	}
};

// 批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysHrInterviewPoolView) => x.ID) as (string | number)[];

	if (selectedIds && selectedIds.length > 0) {
		loading.value = true;
		try {
			await api().delete(selectedIds);
			tableRef.value?.clearSelection();
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy?.$t('message._system.common.vm.error') || '操作失败');
		} finally {
			loading.value = false;
		}
	} else {
		ElMessage.error(ci.proxy?.$t('message._system.common.vm.check') || '请选择要删除的数据');
	}
};

// 批量录用
const onBatchOnboarding = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysHrInterviewPoolView) => x.ID) as (string | number)[];

	if (selectedIds && selectedIds.length > 0) {
		loading.value = true;
		try {
			await api()
				.batchOnboarding(selectedIds)
				.then((res) => {
					if (res.Code === 200) {
						ElMessage.success('批量录用成功');
						tableRef.value?.clearSelection();
						getTableData();
					} else {
						ElMessage.error((res.Message as unknown as string) || '批量录用失败');
					}
				});
		} catch (error) {
			ElMessage.error(ci.proxy?.$t('message._system.common.vm.error') || '操作失败');
		} finally {
			loading.value = false;
		}
	} else {
		ElMessage.error(ci.proxy?.$t('message._system.common.vm.check') || '请选择要录用的数据');
	}
};

// 导出操作
const onExport = () => {
	const selected = tableRef.value?.getSelectedRows();
	if (selected && selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 加载选择列表数据
const loadSelectListData = async () => {
	try {
		const [bills] = await Promise.allSettled([other.getSelectList(API_ENDPOINTS.BILLS, [], false)]);

		// 处理选择列表结果，即使部分失败也继续
		if (bills.status === 'fulfilled') stateData.AllSysHrInterviewRequestBills = bills.value;
	} catch (error) {
		// 静默处理错误
	}
};

// ============ 行内编辑功能 ============

/**
 * 验证工号是否为纯数字
 */
const validateStaffNo = (staffNo: string): boolean => {
	if (!staffNo) return true; // 允许为空
	return /^\d+$/.test(staffNo.toString());
};

/**
 * 处理行编辑开始事件
 */
const onRowEdit = (rowIndex: number, rowData: any) => {
	// 开始编辑行
};

/**
 * 处理单行保存事件
 */
const onRowSave = async (rowIndex: number, rowData: any, originalData: any) => {
	try {
		loading.value = true;

		// 验证工号格式
		if (rowData.HiredStaffNo && !validateStaffNo(rowData.HiredStaffNo)) {
			ElMessage.error('工号只能输入数字');
			return;
		}

		// 构造批量编辑数据
		const batchData = [
			{
				id: rowData.ID,
				newHiredStaffNo: rowData.HiredStaffNo,
			},
		];

		const result = await api().batchUpdateHiredStaffNo(batchData);

		if (result?.Code === 200) {
			ElMessage.success('保存成功');
			// 刷新表格数据
			await getTableData();
		} else {
			ElMessage.error(result?.Message || '保存失败');
			other.setFormError(ci, result);
		}
	} catch (error: any) {
		ElMessage.error(error?.message || '保存失败');
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
	}
};

/**
 * 处理行编辑取消事件
 */
const onRowCancel = (rowIndex: number, originalData: any) => {
	// 取消编辑行
};

/**
 * 处理批量保存事件（批量修改工号）
 */
const onBatchSave = async (editedRows: Array<{ index: number; data: any; original: any }>) => {
	try {
		loading.value = true;

		// 筛选出工号有变更的数据
		const staffNoChanges = editedRows.filter((row) => row.data.HiredStaffNo !== row.original.HiredStaffNo);

		if (staffNoChanges.length === 0) {
			ElMessage.warning('没有检测到工号变更，无需保存');
			return;
		}

		// 验证所有变更的工号格式
		const invalidStaffNos = staffNoChanges.filter((row) => row.data.HiredStaffNo && !validateStaffNo(row.data.HiredStaffNo));
		if (invalidStaffNos.length > 0) {
			ElMessage.error('工号只能输入数字，请检查后重新保存');
			return;
		}

		// 构造批量修改工号的数据格式
		const batchData = staffNoChanges.map((row) => ({
			id: row.data.ID,
			newHiredStaffNo: row.data.HiredStaffNo,
		}));

		// 调用批量修改工号接口
		const result = await api().batchUpdateHiredStaffNo(batchData);

		if (result?.Code === 200) {
			ElMessage.success(`批量修改工号成功，共修改 ${staffNoChanges.length} 条记录`);
		} else {
			ElMessage.error(result?.Message || '批量修改工号失败');
		}
		// 刷新表格数据
		await getTableData();
	} catch (error: any) {
		ElMessage.error(error?.message || '批量修改工号失败');
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;

	// 如果有entityId，自动设置搜索条件
	if (props.entityId) {
		searchData.value.InterviewRequestBillId = props.entityId;
	}

	try {
		// 并行加载选择列表数据和表格数据
		await Promise.all([loadSelectListData(), getTableData()]);
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
	}
});
</script>
